<template>
    <div class="background" @click="toggleLogin"></div>
    <div class="login">
        <div class="login-title">
            <h1>登录</h1>
        </div>
        <div class="login-form">
            <!-- 绑定提交方法 -->
            <form @submit.prevent="toLogin" method="post">
                <el-input type="text" v-model="username" placeholder="请输入账号" />
                <el-input type="password" v-model="password" show-password placeholder="请输入密码" />
                <button :disabled="isSubmitting" v-loading="loading">登录</button>
            </form>
        </div>
        <div class="footer">
            <span @click="showMsg('请联系管理员')">忘记密码</span>
            <span @click="showMsg()">注册</span>
        </div>
        <el-icon class="close-icon" @click="toggleLogin">
            <CloseBold />
        </el-icon>
    </div>
    <div class="reset">
        <!-- 忘记密码重置密码 -->
        <div class="reset-title">
            <h1>修改密码</h1>
        </div>
        <div class="reset-form">
            <el-form ref="formRef" :rules="rules" :model="ruleForm" label-width="80px" label-position="right" status-icon hide-required-asterisk>

                <el-form-item label="账号" prop="username">
                    <el-input v-model="ruleForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="ruleForm.oldPassword" type="password" placeholder="请输入原密码"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" placeholder="请输入新密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="ruleForm.confirmPassword" autocomplete="off" type="password"
                        placeholder="请再次输入密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="changePasswd" :disabled="isSubmitting" v-loading="loading">确认修改</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-icon class="close-icon" @click="toggleLogin">
            <CloseBold />
        </el-icon>
    </div>
    <div class="reg" v-show="false">
        <div class="reg-title">
            <h1>注册</h1>
        </div>
        <div class="reg-form">
            <form action="">
                <input type="text" placeholder="请输入账号">
                <input type="password" placeholder="请输入密码">
                <input type="password" placeholder="请再次输入密码">
                <button>注册</button>
            </form>
        </div>
        <div class="footer">
            <a href="">已有账号，去登录</a>
        </div>
    </div>
</template>
<script setup>
import { ref } from 'vue'
import gsap from 'gsap'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { PutMyPassword } from '@/api/front/contest';

const loading = ref(false)
const isSubmitting = ref(false)

const username = ref('')
const password = ref('')
const store = useStore()
const emits = defineEmits(['role'])
const isLogin = ref(false)
const isForget = ref(false)
const formRef = ref(null)
const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入新密码'));
    } else {
        callback();
    }
};
const validatePass2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'));
    } else if (value !== ruleForm.value.password) {
        callback(new Error('两次输入密码不一致!'));
    } else {
        callback();
    }
};
const ruleForm = ref({
    userId: store.state.userInfo.userId,
    username: store.state.userInfo.username,
    oldPassword: '',
    password: '',
    confirmPassword: ''
})
const rules = {
    oldPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    password: [
        { required: true, validator: validatePass, trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, validator: validatePass2, trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ]
}

// 关闭弹窗
const toggleLogin = (action, el) => {
    // 使用gsap给Login 渐入渐出动画
    if (action == 'open') {
        isLogin.value = !isLogin.value
        if (el == 'login') {
            gsap.to('#app>.login', {
                duration: 0.5,
                opacity: 1,
                display: 'flex',
                transform: 'translate(-45%, -50%)',
            })
        }
        if (el == 'reset') {
            gsap.to('#app>.reset', {
                duration: 0.5,
                opacity: 1,
                display: 'flex',
                transform: 'translate(-45%, -50%)',
            })
        }
        gsap.to('#app>.background', {
            duration: 0.5,
            opacity: 1,
            display: 'block',
        })

    } else {
        isLogin.value = !isLogin.value
        username.value = ''
        password.value = ''
        gsap.to('#app>.login', {
            duration: 0.3,
            opacity: 0,
            display: 'none',
            transform: 'translate(-55%, -50%)',
        })
        gsap.to('#app>.reset', {
            duration: 0.3,
            opacity: 0,
            display: 'none',
            transform: 'translate(-55%, -50%)',
        })
        gsap.to('#app>.background', {
            duration: 0.3,
            opacity: 0,
            display: 'none',
        })
    }
    // console.log(isLogin.value)

}
const toggleReset = () => {
    if (isForget.value) {
        isForget.value = !isForget.value
        gsap.to('#app>.reset', {
            duration: 0.1,
            opacity: 0,
            display: 'none',
            transform: 'translate(-55%, -50%)',
        })
        gsap.to('#app>.login', {
            duration: 0.5,
            opacity: 1,
            display: 'flex',
            transform: 'translate(-45%, -50%)',
        })

    } else {
        isForget.value = !isForget.value
        gsap.to('#app>.login', {
            duration: 0.1,
            opacity: 0,
            display: 'none',
            transform: 'translate(-55%, -50%)',
        })
        // 打开重置密码框
        gsap.to('#app>.reset', {
            duration: 0.5,
            opacity: 1,
            display: 'flex',
            transform: 'translate(-45%, -50%)',
        })
    }
}
// 登录
const toLogin = async () => {
    loading.value = true
    isSubmitting.value = true
    await axios.post('https://api.saike.qqwj.live/login', {
        username: username.value,
        password: password.value
    }).then(res => {
        if (res.status === 200) {
            const token = res.data.token; // 从响应中获取Token 
            const resData = res.data.userData[0];
            console.log('res:', res.data)
            // 登录成功
            const userInfo = {
                userId: resData.userId,
                roleId: resData.roleId,
                role: '',
                username: resData.username,
                nickname: resData.nickName,
                phone: resData.phone,
                avatar: resData.profilePath,
                synopsis: resData.synopsis,
                academy: resData.academy,
                token: token
            }
            ruleForm.value.username = resData.username
            ruleForm.value.userId = resData.userId
            switch (userInfo.roleId) {
                case 0:
                    userInfo.role = 'admin'
                    break;
                case 1:
                    userInfo.role = 'teacher'
                    break;
                case 2:
                    userInfo.role = 'judge'
                    break;
                case 3:
                    userInfo.role = 'audience'
                    break;
                default:
                    break;
            }
            // 登录成功后，将登录状态改为true
            store.commit('setLoginState', true)
            // 将用户信息存储到vuex
            store.commit('setUserInfo', userInfo)
            localStorage.setItem('userInfo', JSON.stringify(userInfo));
            console.log(store.state.userInfo)
            emits('role', userInfo.role)
            // 关闭登录框
            toggleLogin()
            // 提示登录成功
            ElMessage({
                message: `登录成功`,
                type: 'success',
                duration: 1000,
            });
        } else {
            // 登录失败
            ElMessage({
                message: `登录失败`,
                type: 'error',
                duration: 1000,
            });
        }
    }).catch(err => {
        // 登录失败
        if (err.response.status == 401) {
            ElMessage({
                message: `登录失败，用户名或密码错误`,
                type: 'error',
                duration: 1000,
            });
            return
        }
        ElMessage({
            
            message: `错误`,
            type: 'error',
            duration: 1000,
        });
        console.log(err)
    })
    loading.value = false
    isSubmitting.value = false
}
// 修改密码
const changePasswd = async () => {
    console.log(ruleForm.value)
    isSubmitting.value = true
    loading.value = true
    const res = await PutMyPassword(ruleForm.value)
    console.log(res)
    if (res.data == '修改成功') {
        ElMessage({
            message: `修改成功`,
            type: 'success',
            duration: 1000,
        });
        toggleLogin('close', 'all')
    } else if (res.data == '密码修改失败，原用户名或原密码错误') {
        ElMessage({
            message: `密码修改失败，原用户名或原密码错误`,
            type: 'error',
            duration: 1000,
        });
    }
    isSubmitting.value = false
    loading.value = false 
}

// 弹些消息
const showMsg = (msg) => {
    if(msg) {
        ElMessage({
            message: msg,
            type: 'warning',
            duration: 1000,
        });
        return;
    }

    ElMessage({
        message: `功能暂未开放`,
        type: 'warning',
        duration: 1000,
    });

}

// 暴露给父组件的方法
defineExpose({
    toggleLogin,
    toggleReset
})


</script>
<style scoped lang="scss">
.background {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.3);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    display: none;
}

.login,
.reg,
.reset {
    width: 400px;
    height: 500px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 25px;
    padding: 0 50px;
    box-sizing: border-box;
    position: fixed;
    z-index: 2;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: none;
    opacity: 0;

    .login-title {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;

        h1 {
            font-size: 30px;
            color: #333;
            padding: 10px;
            border-bottom: #42b983 3px solid;

        }
    }

    .login-form {
        width: 100%;
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;

        form {
            width: 300px;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;

            input {
                width: 100%;
                height: 40px;
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 0 10px;
                outline: none;
                box-sizing: border-box;
            }
            :deep(.el-input) {
                width: 100%;
                height: 40px;
                --el-input-focus-border-color: #42b983;
            }

            button {
                width: 100%;
                height: 40px;
                border: none;
                border-radius: 5px;
                background-color: #42b983;
                color: #fff;
                font-size: 16px;
                cursor: pointer;
                outline: none;
                padding: 0 10px;

                &:hover {
                    background-color: #42b983c4;
                }
            }
        }
    }

    .footer {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        span {
            font-size: 16px;
            color: #42b983;
            cursor: pointer;
            text-decoration: none;

            &:hover {
                text-decoration: underline;
            }
        }
    }

    .close-icon {
        position: absolute;
        right: 20px;
        top: 20px;
        cursor: pointer;
    }
}

.reset {
    .reset-title {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;

        h1 {
            font-size: 30px;
            color: #333;
            padding: 10px;
            border-bottom: #42b983 3px solid;
        }
    }

    .reset-form {
        width: 100%;
        height: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 20px;

        form {
            width: 300px;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;

            input {
                width: 100%;
                height: 40px;
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 0 10px;
                outline: none;
                box-sizing: border-box;
            }

            button {
                width: 100%;
                height: 40px;
                border: none;
                border-radius: 5px;
                background-color: #42b983;
                color: #fff;
                font-size: 16px;
                cursor: pointer;
                outline: none;
                padding: 0 10px;

                &:hover {
                    background-color: #42b983c4;
                }
            }
        }
    }

    .reset-footer {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        span {
            font-size: 16px;
            color: #42b983;
            cursor: pointer;
            text-decoration: none;

            &:hover {
                text-decoration: underline;
            }
        }
    }
}

.reg {

    .reg-title {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;

        h1 {
            font-size: 30px;
            color: #333;
        }
    }

    .reg-form {
        width: 100%;
        height: 300px;
        display: flex;
        align-items: center;
        justify-content: center;

        form {
            width: 300px;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;

            input {
                width: 100%;
                height: 40px;
                border: 1px solid #ccc;
                border-radius: 5px;
                padding: 0 10px;
                outline: none;
            }

            button {
                width: 100%;
                height: 40px;
                border: none;
                border-radius: 5px;
                background-color: #42b983;
                color: #fff;
                font-size: 16px;
                cursor: pointer;
                outline: none;
            }
        }
    }

    .reg-footer {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;

        a {
            font-size: 16px;
            color: #42b983;
            cursor: pointer;

            &:hover {
                text-decoration: underline;
            }
        }
    }
}
</style>